package com.jsyso.jsyso.web.method.support;

import java.util.Map;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.jsyso.jsyso.util.JsMap;
import com.jsyso.jsyso.web.JsMapParam;

/**
 * JsMap请求参数处理
 * @author janjan, xujian_jason@163.com
 *
 */
public class JsMapMethodArgumentResolver implements HandlerMethodArgumentResolver {

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return JsMapParam.class.isAssignableFrom(parameter.getParameterType());
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		Class<?> paramType = parameter.getParameterType();
		Map<String, String[]> parameterMap = webRequest.getParameterMap();
		if(JsMapParam.class.isAssignableFrom(paramType)) {
			JsMap result = JsMap.create(parameterMap.size());
			for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
				if (entry.getValue().length > 0) {
					String[] values = entry.getValue();
					result.put(entry.getKey(), values.length > 1 ? values : values[0]);
				}
			}
			return JsMapParam.create(result);
		}
		return JsMapParam.create(JsMap.create(0));
	}

}
